import { program } from 'commander'
import { resolve } from 'path'
import { jsonDirToExcel } from './index'

interface CliOpts {
  input: string
  output: string
  sheet: string
  flatten: boolean
  recursive: boolean
  pattern: string
  exportMode: string
}

program
  .name('json2excel')
  .description('Convert JSON folder to Excel (ESM & CommonJS)')
  .version('1.0.0')
  .requiredOption('-i, --input <dir>', 'input directory')
  .option('-o, --output <file>', 'output xlsx', './output.xlsx')
  .option('-s, --sheet <name>', 'sheet name', 'Data')
  .option('-f, --no-flatten', 'disable flatten')
  .option('-r, --recursive', 'scan subdirs')
  .option('-p, --pattern <regex>', 'file pattern', '\\.json$')
  .option('-m, --export-mode <mode>', 'horizontal | vertical', 'horizontal')
  .action(async (opts: CliOpts) => {
    // ← 显式类型
    await jsonDirToExcel({
      inputDir: resolve(opts.input),
      outputFile: resolve(opts.output),
      sheetName: opts.sheet,
      flatten: opts.flatten,
      includeSubdirs: opts.recursive,
      filePattern: new RegExp(opts.pattern, 'i'),
      exportMode: opts.exportMode === 'vertical' ? 'vertical' : 'horizontal',
    })
    console.log('✅ Excel saved →', resolve(opts.output))
  })

program.parse()
